﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Web;
using System.Collections.Specialized;
using LiveNet.Configuration;

namespace LiveNet.Authentication
{
    public static class DomainAuthentication
    {
        private const string PERMISSIONURL = "https://ux.cumulus.services.live.com/pgux/default.aspx";

        public static Uri SpacesPermissionUrl
        {
            get
            {
                ConfigurationSectionHandler section = ConfigurationSectionHandler.Get();

                Uri permissionUrl = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}?rl={1}&pl={2}&ps={3}{4}",
                                                     PERMISSIONURL,
                                                     MakeUrlAbsolute(section.SpacesAuthorization.PermissionReturnUrl),
                                                     MakeUrlAbsolute(section.SpacesAuthorization.PrivacyUrl),
                                                     section.SpacesAuthorization.PermissionString,
                                                     section.SpacesAuthorization.UseHttps ? string.Empty : "&NoSSL"));

                return permissionUrl;
            }
        }

        //public static Uri ContactsPermissionUrl
        //{
        //    get
        //    {
        //        ConfigurationSectionHandler section = ConfigurationSectionHandler.Get();

        //        Uri permissionUrl = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}?rl={1}&pl={2}&ps={3}{4}",
        //                                             PERMISSIONURL,
        //                                             MakeUrlAbsolute(section.ContactsAuthorization.PermissionReturnUrl),
        //                                             MakeUrlAbsolute(section.ContactsAuthorization.PrivacyUrl),
        //                                             section.ContactsAuthorization.PermissionString,
        //                                             section.ContactsAuthorization.UseHttps ? string.Empty : "&NoSSL"));

        //        return permissionUrl;
        //    }
        //}


        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")]
        private static Uri MakeUrlAbsolute(string url)
        {
            if (url.StartsWith("~"))
            {
                return new Uri(string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}",
                                     HttpContext.Current.Request.Url.Scheme,
                                     HttpContext.Current.Request.Url.Authority,
                                     (HttpContext.Current.Request.ApplicationPath + url.Substring(1)).Replace("//", "/")));
            }
            
            return new Uri(url);
        }

        /// <summary>
        /// Reads the form POST data for the current <see cref="HttpRequest"/> and obtains the authorization
        /// token and owner handle.
        /// </summary>
        public static DomainAuthenticationResponse ProcessAuthenticationResponse()
        {
            NameValueCollection postedValues = HttpContext.Current.Request.Form;

            string domainAuthToken = postedValues["DomainAuthenticationToken"];
            string ownerHandle = postedValues["OwnerHandle"];
            object o = Enum.Parse(typeof(DomainAuthenticationResponseCode), postedValues["ResponseCode"], true);

            if (o == null)
            {
                throw new LiveNetException("Authentication ResponseCode is unknown.");
            }

            DomainAuthenticationResponseCode responseCode = (DomainAuthenticationResponseCode)o;

            if (responseCode == DomainAuthenticationResponseCode.RequestApproved)
            {
                //OK, get information with ownerHandle and domainAuthToken
                return new DomainAuthenticationResponse(ownerHandle, domainAuthToken, responseCode);
            }
            else
            {
                //error, display responseCode
                return new DomainAuthenticationResponse(responseCode);
            }
        }
    }
}